<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="商品名称" prop="goodsName">
        <el-input
          v-model="queryParams.goodsName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品ID" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入商品ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品编码" prop="identifier">
        <el-input
          v-model="queryParams.identifier"
          placeholder="请输入商品编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品条码" prop="barCode">
        <el-input
          v-model="queryParams.barCode"
          placeholder="请输入商品编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="采购员" prop="purchase">
        <el-input
          v-model="queryParams.purchase"
          placeholder="请输入采购负责人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上架状态" prop="marketEnable">
        <el-select
          v-model="queryParams.marketEnable"
          placeholder="上架状态"
          clearable
        >
          <el-option
            v-for="dict in dict.type.goods_market_enable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          clearable
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="分类状态" prop="haveCategory">
        <el-select
          v-model="queryParams.paramMap.haveCategory"
          placeholder="分类状态"
          clearable
        >
          <el-option label="有" :value="true" />
          <el-option label="无" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item label="商品分类" prop="categoryPath">
        <treeselect
          v-model="categoryPaths.categoryPath"
          :options="categoryList"
          style="width: 200px; margin-right: 100px"
          placeholder="请选择商品分类"
          :disabled="!queryParams.paramMap.haveCategory"
          @select="changeCategoryPath"
          clearable
        />
      </el-form-item>
      <el-form-item label="库存状态" prop="haveQuantity">
        <el-select
          v-model="queryParams.paramMap.haveQuantity"
          placeholder="库存状态"
          clearable
        >
          <el-option label="有" :value="true" />
          <el-option label="无" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item label="主图状态" prop="original">
        <el-select
          v-model="queryParams.paramMap.haveOriginal"
          placeholder="库存状态"
          clearable
        >
          <el-option label="有" :value="true" />
          <el-option label="无" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item label="限购方式">
        <el-select
          v-model="queryParams.limitMode"
          placeholder="限购方式"
          clearable
        >
          <el-option
            v-for="dict in dict.type.qualitygoods_limit_mode"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="广告品种" prop="recommend">
        <el-select
          v-model="queryParams.recommend"
          placeholder="广告品种,精准匹配"
          clearable
        >
          <el-option label="是" value="true" />
          <el-option label="否" value="false" />
        </el-select>
      </el-form-item>
      <el-form-item label="诊疗专区" prop="seasonal">
        <el-select
          v-model="queryParams.seasonal"
          placeholder="应季热销,精准匹配"
          clearable
        >
          <el-option label="是" value="true" />
          <el-option label="否" value="false" />
        </el-select>
      </el-form-item>
      <el-form-item label="OTC专销" prop="proprietary">
        <el-select
          v-model="queryParams.proprietary"
          placeholder="OTC专销,精准匹配"
          clearable
        >
          <el-option label="是" value="true" />
          <el-option label="否" value="false" />
        </el-select>
      </el-form-item>
      <el-form-item label="控销品种" prop="control">
        <el-select
          v-model="queryParams.control"
          placeholder="控销品种,精准匹配"
          clearable
        >
          <el-option label="是" value="true" />
          <el-option label="否" value="false" />
        </el-select>
      </el-form-item>
      <el-form-item label="开票员专销" prop="preferred">
        <el-select
          v-model="queryParams.preferred"
          placeholder="开票员专销,精准匹配"
          clearable
        >
          <el-option label="是" value="true" />
          <el-option label="否" value="false" />
        </el-select>
      </el-form-item>
      <el-form-item label="中药饮片" prop="traditional">
        <el-select
          v-model="queryParams.traditional"
          placeholder="中药饮片,精准匹配"
          clearable
        >
          <el-option label="是" value="true" />
          <el-option label="否" value="false" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="展示图状态" prop="imageList">
        <el-select v-model="queryParams.paramMap.imageList" placeholder="库存状态">
          <el-option label="有" :value="true" />
          <el-option label="无" :value="false" />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleEditTable(undefined)"
          v-hasPermi="['goods:goods:sku:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleEditTable"
          v-hasPermi="['goods:goods:sku:edit']"
          >修改</el-button
        >
      </el-col>
      <!-- </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['goods:goods:export']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <!-- :disabled="!synchronizeOrders" -->
        <el-button
          type="success"
          plain
          icon="el-icon-grape"
          size="mini"
          @click="handleSynchronizeQuantity"
          v-hasPermi="['goods:sku:sync:erp']"
          >同步库存</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-grape"
          size="mini"
          @click="deleteCatchQuantity"
          v-hasPermi="['goods:goods:sku:quantity:cache:delete']"
          >清空缓存中的库存</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
        :columns="columns"
      >
      </right-toolbar>
    </el-row>

    <el-table
      border
      v-loading="loading"
      :data="goodsSkuList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <template v-for="(column,index) in columns">
        <template v-if="column.key == 'marketEnable'">
          <el-table-column :label="column.label" align="center" :width="column.width" v-if="column.visible" :index="index">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.marketEnable"
                active-value="UPPER"
                inactive-value="DOWN"
                @change="handleMarketEnableStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
        </template>
        <template v-else-if="column.key == 'recommend'">
          <el-table-column :label="column.label" align="center" :width="column.width" v-if="column.visible" :index="index">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.recommend"
                @change="handleRecommendStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
        </template>
        <template v-else-if="column.key == 'createTime'">
          <el-table-column :label="column.label" align="center" :prop="column.key" :width="column.width" v-if="column.visible" :index="index">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
        </template>
        <template v-else>
          <el-table-column :label="column.label" :prop="column.prop" :width="column.width" v-if="column.visible" :index="index" />
        </template>
      </template>-->

      <el-table-column
        :label="columns[0].label"
        align="left"
        :prop="columns[0].prop"
        :width="columns[0].width"
        :show-overflow-tooltip="true"
        v-if="columns[0].visible"
      />
      <el-table-column
        :label="columns[1].label"
        align="center"
        :prop="columns[1].prop"
        :show-overflow-tooltip="true"
        :width="columns[1].width"
        v-if="columns[1].visible"
      />
      <el-table-column
        :label="columns[2].label"
        align="center"
        prop="price"
        :show-overflow-tooltip="true"
        :width="columns[2].width"
        v-if="columns[2].visible"
      />
      <el-table-column
        :label="columns[3].label"
        align="center"
        prop="identifier"
        :show-overflow-tooltip="true"
        :width="columns[3].width"
        v-if="columns[3].visible"
      />
      <el-table-column
        :label="columns[4].label"
        align="center"
        prop="barCode"
        :width="columns[4].width"
        :show-overflow-tooltip="true"
        v-if="columns[4].visible"
      />
      <el-table-column
        :label="columns[5].label"
        align="center"
        prop="simpleSpecs"
        :width="columns[5].width"
        :show-overflow-tooltip="true"
        v-if="columns[5].visible"
      />
      <el-table-column
        :label="columns[6].label"
        align="center"
        prop="quantity"
        :width="columns[6].width"
        :show-overflow-tooltip="true"
        v-if="columns[6].visible"
      />
      <el-table-column
        :label="columns[7].label"
        align="center"
        :width="columns[7].width"
        :show-overflow-tooltip="true"
        v-if="columns[7].visible"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.marketEnable"
            active-value="UPPER"
            inactive-value="DOWN"
            @change="handleMarketEnableStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        :label="columns[8].label"
        align="center"
        prop="categoryName"
        :width="columns[8].width"
        v-if="columns[8].visible"
      />

      <el-table-column
        :label="columns[9].label"
        align="center"
        :prop="columns[9].prop"
        :width="columns[9].width"
        v-if="columns[9].visible"
      />
      <el-table-column
        :label="columns[10].label"
        align="center"
        :width="columns[10].width"
        v-if="columns[10].visible"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.seasonal"
            @change="
              changeCeilingStatus(
                scope.row,
                columns[10].prop,
                columns[10].label
              )
            "
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        :label="columns[11].label"
        align="center"
        prop="manufacturer"
        :show-overflow-tooltip="true"
        :width="columns[11].width"
        v-if="columns[11].visible"
      />
      <el-table-column
        :label="columns[12].label"
        align="center"
        :prop="columns[12].prop"
        :show-overflow-tooltip="true"
        :width="columns[12].width"
        v-if="columns[12].visible"
      />
      <el-table-column
        :label="columns[13].label"
        align="center"
        :width="columns[13].width"
        v-if="columns[13].visible"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.recommend"
            @change="
              changeCeilingStatus(
                scope.row,
                columns[13].prop,
                columns[13].label
              )
            "
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        :label="columns[14].label"
        align="center"
        :prop="columns[14].prop"
        :width="columns[14].width"
        :show-overflow-tooltip="true"
        v-if="columns[14].visible"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="columns[15].label"
        align="center"
        prop="id"
        :width="columns[15].width"
        v-if="columns[15].visible"
      ></el-table-column>
      <el-table-column
        :label="columns[16].label"
        align="center"
        prop="original"
        :width="columns[16].width"
        v-if="columns[16].visible"
      >
        <template slot-scope="scope">
          <el-image
            style="width: 30px"
            :src="scope.row.original"
            @click="clickOriginal(scope.row)"
            :preview-src-list="scope.row.originals"
          >
          </el-image>
        </template>
      </el-table-column>

      <el-table-column
        :label="columns[17].label"
        align="center"
        :width="columns[17].width"
        v-if="columns[17].visible"
      ></el-table-column>
      <el-table-column
        :label="columns[18].label"
        align="center"
        :prop="columns[18].prop"
        :show-overflow-tooltip="true"
        :width="columns[18].width"
        v-if="columns[18].visible"
      />
      <el-table-column
        :label="columns[19].label"
        align="center"
        :width="columns[19].width"
        v-if="columns[19].visible"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.control"
            @change="
              changeCeilingStatus(
                scope.row,
                columns[19].prop,
                columns[19].label
              )
            "
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        :label="columns[20].label"
        align="center"
        :width="columns[20].width"
        v-if="columns[20].visible"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.preferred"
            @change="
              changeCeilingStatus(
                scope.row,
                columns[20].prop,
                columns[20].label
              )
            "
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        :label="columns[21].label"
        align="center"
        :width="columns[21].width"
        v-if="columns[21].visible"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.traditional"
            @change="
              changeCeilingStatus(
                scope.row,
                columns[21].prop,
                columns[21].label
              )
            "
          >
          </el-switch>
        </template>
      </el-table-column>

      <el-table-column
        :label="columns[22].label"
        align="center"
        :prop="columns[22].prop"
        :show-overflow-tooltip="true"
        :width="columns[22].width"
        v-if="columns[22].visible"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.qualitygoods_limit_mode"
            :value="scope.row.limitMode"
          />
          <!-- <el-select v-model="scope.row.limitMode" placeholder="限购方式" size="mini" clearable
            @change="changeLimitMode(scope.row)">
            <el-option v-for="dict in dict.type.qualitygoods_limit_mode" :key="dict.value"
              :label="dict.label" :value="dict.value" />
          </el-select> -->
        </template>
      </el-table-column>
      <el-table-column
        :label="columns[23].label"
        align="center"
        :prop="columns[23].prop"
        :show-overflow-tooltip="true"
        :width="columns[23].width"
        v-if="columns[23].visible"
      >
        <!-- <template slot-scope="scope">
          <el-input v-model="scope.row.limitNum" size="mini" @change="changeLimitNum(scope.row)"
            clearable />
        </template> -->
      </el-table-column>

      <el-table-column
        :label="columns[24].label"
        align="center"
        :prop="columns[24].prop"
        :show-overflow-tooltip="true"
        :width="columns[24].width"
        v-if="columns[24].visible"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.qualitygoods_limit_mode"
            :value="scope.row.limitMode"
          />
          <!-- <el-select v-model="scope.row.limitMode" placeholder="限购方式" size="mini" clearable
            @change="changeLimitMode(scope.row)">
            <el-option v-for="dict in dict.type.qualitygoods_limit_mode" :key="dict.value"
              :label="dict.label" :value="dict.value" />
          </el-select> -->
        </template>
      </el-table-column>
      <el-table-column
        :label="columns[25].label"
        align="center"
        :prop="columns[25].prop"
        :show-overflow-tooltip="true"
        :width="columns[25].width"
        v-if="columns[25].visible"
      >
        <!-- <template slot-scope="scope">
          <el-input v-model="scope.row.limitNum" size="mini" @change="changeLimitNum(scope.row)"
            clearable />
        </template> -->
      </el-table-column>
      <el-table-column
        :label="columns[26].label"
        align="center"
        :prop="columns[26].prop"
        :show-overflow-tooltip="true"
        :width="columns[26].width"
        v-if="columns[26].visible"
      ></el-table-column>
      <el-table-column
        :label="columns[27].label"
        align="center"
        :prop="columns[27].prop"
        :show-overflow-tooltip="true"
        :width="columns[27].width"
        v-if="columns[27].visible"
      ></el-table-column>
      <el-table-column
        :label="columns[28].label"
        align="center"
        :prop="columns[28].prop"
        :show-overflow-tooltip="true"
        :width="columns[28].width"
        v-if="columns[28].visible"
      ></el-table-column>
      <el-table-column
        :label="columns[29].label"
        align="center"
        :width="columns[29].width"
        :show-overflow-tooltip="true"
        v-if="columns[29].visible"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.evaluate"
            @change="handleEvaluateStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        :label="columns[30].label"
        align="center"
        :width="columns[30].width"
        :show-overflow-tooltip="true"
        v-if="columns[30].visible"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.applyCoupon"
            @change="
              changeCeilingStatus(
                scope.row,
                columns[30].prop,
                columns[30].label
              )
            "
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        :label="columns[31].label"
        align="center"
        :prop="columns[31].prop"
        :show-overflow-tooltip="true"
        :width="columns[31].width"
        v-if="columns[31].visible"
      ></el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="120"
        fixed="right"
      >
        <template slot-scope="scope" v-if="scope.row.roleId !== 1">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEditTable(scope.row)"
            v-hasPermi="['goods:goods:query']"
            >详情</el-button
          >
          <!--
          <el-button size="mini" type="text" icon="el-icon-paperclip" @click="limit(scope.row)"
            v-hasPermi="['goods:goods:sku:limit:edit']">限购</el-button>
          -->
          <el-dropdown
            size="mini"
            @command="(command) => handleCommand(command, scope.row)"
            v-hasPermi="[
              'goods:goods:manualQuantity:edit',
              'goods:goods:sku:limit:edit',
            ]"
          >
            <span class="el-dropdown-link">
              <i class="el-icon-d-arrow-right el-icon--right"></i>更多
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                command="manualQuantity"
                icon="el-icon-truck"
                v-hasPermi="['goods:goods:manualQuantity:edit']"
                >虚拟库存</el-dropdown-item
              >
              <el-dropdown-item
                command="manualPack"
                icon="el-icon-truck"
                v-hasPermi="['goods:goods:manualPack:edit']"
                >调整中包装</el-dropdown-item
              >
              <el-dropdown-item
                command="deleteCatchQuantity"
                icon="el-icon-paperclip"
                v-hasPermi="['goods:goods:sku:quantity:cache:delete']"
                >删除缓存库存</el-dropdown-item
              >
              <el-dropdown-item
                command="limit"
                icon="el-icon-paperclip"
                v-hasPermi="['goods:goods:sku:limit:edit']"
                >限购配置</el-dropdown-item
              >
              <el-dropdown-item command="syncSku" icon="el-icon-paperclip" v-hasPermi="['goods:goods:sku:sync:sku']">同步商品信息</el-dropdown-item>
              <el-dropdown-item command="goodsAlias" icon="el-icon-paperclip" v-hasPermi="['goods:goods:alias:edit']">商品别名</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 打开商品SKU促销状态对话框 -->
    <el-dialog title="确认商品促销价格" :visible.sync="openPromotionFlag" width="400px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col>
            <el-form-item label="促销价格" prop="promotionPrice">
              <el-input-number v-model="form.promotionPrice" controls-position="left" :min="0.01" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="handlePromotionStatusChange(currentRow, form.promotionPrice)"
          >确 定</el-button
        >
        <el-button @click="closePromotionFlagView">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 限制 -->
    <el-dialog
      title="限购"
      :visible.sync="dialogVisible"
      width="400px"
      append-to-body
    >
      <p>
        单次最少购买：
        <el-input v-model="ROWS.leastNum" clearable style="width: 200px" />
      </p>
      <p>
        限购方式：
        <el-select
          v-model="ROWS.limitMode"
          placeholder="限购方式"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.qualitygoods_limit_mode"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </p>
      <p>
        限购数量：
        <el-input v-model="ROWS.limitNum" clearable style="width: 200px" />
      </p>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="determineLimit">确 定 </el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改虚拟库存对话框 -->
    <el-dialog
      v-dialogDragWidth
      v-dialogDragHeight
      v-dialogDrag
      :title="title"
      :visible.sync="manualQuantityView"
      width="550px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="虚拟库存" prop="manualQuantity" class="start">
          <el-input-number
            v-model="form.manualQuantity"
            placeholder="请输入虚拟库存数量"
            :show-overflow-tooltip="true"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="manualQuantity">确 定</el-button>
        <el-button @click="manualQuantityView = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 调整中包装对话框 -->
    <el-dialog v-dialogDragWidth v-dialogDragHeight v-dialogDrag :title="title" :visible.sync="manualPackView" width="550px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="调整中包装" prop="manualPack" class="start">
          <el-input-number
            v-model="form.manualPack"
            placeholder="请输入中包装数量"
            :show-overflow-tooltip="true"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="manualPack">确 定</el-button>
        <el-button @click="manualPackView = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 调整商品别名对话框 -->
    <el-dialog v-dialogDragWidth v-dialogDragHeight v-dialogDrag :title="title"
      :visible.sync="goodsAliasVisible" width="500px">
      <el-input type="textarea" autosize resize v-model="form.alias"> </el-input>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitGoodsAlias">修 改</el-button>
        <el-button @click="goodsAliasVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listGoodsSku,
  changeGoodsSkuMarketEnable,
  updateCeiling,
  updateLimit,
  updateManualQuantity,
  updateManualPack,
  removeCatchQuantity,
  updateEvaluate,
  updateAlias,
} from "@/api/goods/goods";
import { listCategory, treeselect } from "@/api/goods/category";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Goods",
  dicts: ["goods_market_enable", "qualitygoods_limit_mode"],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      openPromotionFlag: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品表格数据
      goodsSkuList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      // 日期范围
      dateRange: [],
      // 列信息
      columns: [
        {
          key: 0,
          label: `商品名称`,
          prop: "goodsName",
          width: 200,
          visible: true,
        },
        {
          key: 1,
          label: `品类`,
          prop: "classification",
          width: 100,
          visible: false,
        },
        { key: 2, label: `售价`, prop: "price", width: 80, visible: true },
        { key: 3, label: `编码`, prop: "identifier", width: 80, visible: true },
        { key: 4, label: `条码`, prop: "barCode", width: 150, visible: true },
        {
          key: 5,
          label: `规格`,
          prop: "simpleSpecs",
          width: 100,
          visible: true,
        },
        { key: 6, label: `库存`, prop: "quantity", width: 70, visible: true },
        {
          key: 7,
          label: `上架状态`,
          prop: "marketEnable",
          width: 80,
          visible: true,
        },
        {
          key: 8,
          label: `所属分类`,
          prop: "categoryName",
          width: 100,
          visible: false,
        },
        {
          key: 9,
          label: `有效期`,
          prop: "expirationDate",
          width: 100,
          visible: true,
        },
        {
          key: 10,
          label: `诊疗专区`,
          prop: "seasonal",
          width: 80,
          visible: false,
        },
        {
          key: 11,
          label: `生产厂家`,
          prop: "manufacturer",
          width: 180,
          visible: true,
        },
        {
          key: 12,
          label: `助记码`,
          prop: "mnemonicCode",
          width: 150,
          visible: false,
        },
        {
          key: 13,
          label: `广告品种`,
          prop: "recommend",
          width: 80,
          visible: false,
        },
        {
          key: 14,
          label: `创建时间`,
          prop: "createTime",
          width: 180,
          visible: false,
        },
        { key: 15, label: `商品ID`, prop: "id", width: 180, visible: false },
        { key: 16, label: `主图`, prop: "original", width: 60, visible: true },
        { key: 17, label: `含麻`, prop: "ephedrine", width: 60, visible: true },
        {
          key: 18,
          label: `OTC专销`,
          prop: "proprietary",
          width: 80,
          visible: false,
        },
        {
          key: 19,
          label: `控销品种`,
          prop: "control",
          width: 80,
          visible: false,
        },
        {
          key: 20,
          label: `开票员专销`,
          prop: "preferred",
          width: 90,
          visible: false,
        },
        {
          key: 21,
          label: `中药饮片`,
          prop: "traditional",
          width: 80,
          visible: false,
        },
        {
          key: 22,
          label: `限购方式(1)`,
          prop: "limitMode",
          width: 120,
          visible: false,
        },
        {
          key: 23,
          label: `限购数量(1)`,
          prop: "limitNum",
          width: 100,
          visible: false,
        },
        {
          key: 24,
          label: `限购方式(2)`,
          prop: "limitMode1",
          width: 120,
          visible: false,
        },
        {
          key: 25,
          label: `限购数量(2)`,
          prop: "limitNum1",
          width: 100,
          visible: false,
        },
        { key: 26, label: `中包装`, prop: "pack", width: 75, visible: true },
        {
          key: 27,
          label: `调整中包装`,
          prop: "manualPack",
          width: 90,
          visible: false,
        },
        {
          key: 28,
          label: `虚拟库存`,
          prop: "manualQuantity",
          width: 75,
          visible: false,
        },
        {
          key: 29,
          label: `到手约`,
          prop: "evaluate",
          width: 75,
          visible: true,
        },
        {
          key: 30,
          label: `可用优惠券`,
          prop: "applyCoupon",
          width: 90,
          visible: true,
        },
        {
          key: 31,
          label: `采购员`,
          prop: "purchase",
          width: 80,
          visible: true,
        },
      ],
      // 商品分类列表
      categoryOptions: [],
      // 当前行数据
      currentRow: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        goodsName: "",
        id: "",
        identifier: "",
        barCode: "",
        marketEnable: "",
        recommend: "",
        seasonal: "",
        goodsType: "NORMAL,GIFT",
        paramMap: {},
      },
      categoryPaths: {},
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        promotionPrice: [
          { required: true, message: "促销价格不能为空", trigger: "blur" },
        ],
        manualQuantity: [
          { required: true, message: "虚拟库存不能为空", trigger: "blur" },
        ],
      },
      categoryList: [],
      ROWS: {},
      dialogVisible: false,
      limits: {},
      manualQuantityView: false,
      manualPackView: false,

      goodsAliasVisible: false,
    };
  },
  created() {
    this.listGoodsCategory();
    this.getCategoryTreeselect();
  },
  methods: {
    // // 限购方式
    // changeLimitMode (row) {
    //   console.log(row.limitMode)
    //   updateLimit(row.id, { limitMode: row.limitMode }).then(res => {
    //     if (res.code === 200) {
    //       this.dialogVisible = false
    //     }
    //   })
    // },
    // // 限购数量
    // changeLimitNum (row) {
    //   console.log(row.limitNum)
    //   updateLimit(row.id, { limitNum: row.limitNum }).then(res => {
    //     if (res.code === 200) {
    //       this.dialogVisible = false
    //     }
    //   })
    // },

    // 点击图片
    clickOriginal(row) {
      this.$set(row, "originals", [row.original]);
    },
    // limit 限制
    limit(row) {
      this.ROWS = row;
      this.dialogVisible = true;
    },
    // determineLimit 确定
    determineLimit() {
      updateLimit(this.ROWS.id, {
        leastNum: this.ROWS.leastNum,
        limitMode: this.ROWS.limitMode,
        limitNum: this.ROWS.limitNum,
      }).then((res) => {
        if (res.code === 200) {
          this.dialogVisible = false;
        }
      });
    },

    /** 查询商品分类下拉树结构 */
    getCategoryTreeselect() {
      treeselect().then((response) => {
        this.categoryList = response.data;
      });
    },
    // select 选中
    changeCategoryPath(value) {
      // this.queryParams.categoryPath = value.originalId
      this.categoryList.forEach((i) => {
        if (i.id === value.id) {
          this.queryParams.categoryPath = i.originalId;
        } else {
          i.children.forEach((j) => {
            if (j.id === value.id) {
              this.queryParams.categoryPath = i.originalId + "," + j.originalId;
            }
          });
        }
      });
    },
    // 获取数据
    listGoodsCategory() {
      this.loading = true;
      listCategory({}).then((response) => {
        this.categoryOptions = response.data;
        this.loading = false;
        this.getList();
      });
    },
    /** 查询商品列表 */
    getList() {
      this.loading = true;
      if (this.queryParams.identifier) {
        this.queryParams.identifier = this.queryParams.identifier.trim();
      }
      if (this.queryParams.goodsName) {
        this.queryParams.goodsName = this.queryParams.goodsName.trim();
      }

      listGoodsSku(
        0,
        this.addDateRangeWithMap(this.queryParams, this.dateRange, "CreateTime")
      ).then((response) => {
        this.goodsSkuList = response.rows;
        //获取商品分类名称
        this.goodsSkuList.forEach((goodsSku) => {
          let categoryId = goodsSku.categoryPath;
          if (categoryId) {
            let firstIndex = categoryId.lastIndexOf(",");
            if (firstIndex > 0) {
              categoryId = categoryId.substr(firstIndex + 1);
            }
            for (let category of this.categoryOptions) {
              if (category.id == categoryId) {
                goodsSku.categoryName = category.name;
                break;
              }
            }
          }
        });
        this.total = response.total;
        this.loading = false;
      });
    },
    // 上架状态修改
    handleMarketEnableStatusChange(row) {
      let text = row.marketEnable === "UPPER" ? "上架" : "下架";
      this.$modal
        .confirm('确认"' + text + '""' + row.goodsName + '"商品吗？')
        .then(function () {
          return changeGoodsSkuMarketEnable(
            row.goodsId,
            row.id,
            row.marketEnable
          );
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.marketEnable = row.marketEnable === "UPPER" ? "DOWN" : "UPPER";
        });
    },
    //商品促销状态窗口 打开
    openPromotionFlagView(row) {
      if (row.promotionFlag) {
        if (!row.promotionPrice) {
          row.promotionPrice = row.price;
        }
        this.form.promotionPrice = row.promotionPrice;

        this.currentRow = row;
        this.openPromotionFlag = true;
      } else {
        this.handlePromotionStatusChange(row, row.promotionPrice);
      }
    },
    //商品促销状态窗口 关闭
    closePromotionFlagView() {
      this.openPromotionFlag = false;
      this.currentRow.promotionFlag = !this.currentRow.promotionFlag;
    },
    // 应季状态修改
    changeCeilingStatus(row, property, label) {
      let value = row[property];
      let text = value === true ? label : "取消" + label;

      this.$modal
        .confirm('确认商品"' + row.goodsName + '"' + text + "吗？")
        .then(function () {
          return updateCeiling(row.id, property, { value: value });
        })
        .then(() => {
          this.$modal.msgSuccess("设置" + text + "成功");
        })
        .catch(function () {
          row[property] = !row[property];
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        point: 0,
        remark: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      console.log(this.queryParams.paramMap.haveCategory);
      if (!this.queryParams.paramMap.haveCategory) {
        this.queryParams.categoryPath = "";
        this.categoryPaths = {};
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.queryParams.categoryPath = "";
      this.queryParams.paramMap = {};

      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.roleId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增/修改按钮操作 */
    handleEditTable(row) {
      // let params = {};
      // if (row) {
      //   params = {
      //     pageNum: 1,
      //     id: row.id,
      //     goodsId: row.goodsId,
      //     goodsName: row.goodsName
      //   };
      // }
      // const tabTitle = row ? "修改商品" : "新增商品";
      // this.$tab.openPage(tabTitle, "/goods/editGoodsSku", params);

      this.$router.push("/goods/sku-detail/" + row.id);
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "goods/goods/export",
        {
          ...this.addDateRangeWithMap(
            this.queryParams,
            this.dateRange,
            "CreateTime"
          ),
        },
        `商品列表_${this.parseTime(
          new Date().getTime(),
          "{y}-{m}-{d}_{h}{i}{s}"
        )}.xlsx`
      );
    },
    handleSynchronizeQuantity() {
      //window.open('http://www.xdyy365.com:5003/wholesale/sync-api/order/check', '_black')
      window.open(
        "http://www.xdyy365.com:5003/wholesale/sync-api/sync/goods/kc",
        "_black"
      );
      // axios({ method: 'get', url: 'http://www.xdyy365.com:5003/wholesale/sync-api/order/refresh', }).then(res => {
      //   console.log(res)
      // })
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "manualQuantity":
          this.openManualQuantityView(row);
          break;
        case "manualPack":
          this.openManualPackView(row);
          break;
        case "deleteCatchQuantity":
          this.deleteCatchQuantity(row);
          break;
        case "limit":
          this.limit(row);
          break;
        case "syncSku":
          this.syncSku(row);
          break;
        case "syncQuantity":
          this.syncQuantity(row);
          break;
        case "goodsAlias":
          this.openGoodsAliasView(row);
          break;
        default:
          break;
      }
    },
    openGoodsAliasView(row){
      this.title = "修改商品“" + row.goodsName + "”的搜索关键词/别名";
      this.form = { ...row };
      this.goodsAliasVisible = true;
    },
    openManualQuantityView(row) {
      this.title = "调整“" + row.goodsName + "”的虚拟库存";
      this.form = { ...row };
      this.manualQuantityView = true;
    },
    openManualPackView(row) {
      this.title = "调整“" + row.goodsName + "”的中包装";
      this.form = { ...row };
      this.manualPackView = true;
    },
    //调整虚拟库存
    manualQuantity(row) {
      const _this = this;
      this.$modal
        .confirm("确认调整虚拟库存吗？")
        .then(function () {
          updateManualQuantity(_this.form.id, _this.form.manualQuantity).then(
            function () {
              _this.$modal.msgSuccess("调整虚拟库存成功");
              _this.getList();
              _this.manualQuantityView = false;
            }
          );
        })
        .catch(function (err) {
          console.log(err);
          _this.$modal.msgError("调整虚拟库存出错");
        });
    },
    //调整中包装
    manualPack(row) {
      const _this = this;
      this.$modal
        .confirm("确认调整中包装吗？")
        .then(function () {
          updateManualPack(_this.form.id, _this.form.manualPack).then(
            function () {
              _this.$modal.msgSuccess("调整中包装成功");
              _this.getList();
              _this.manualPackView = false;
            }
          );
        })
        .catch(function (err) {
          console.log(err);
          _this.$modal.msgError("调整中包装出错");
        });
    },
    //删除缓存中的商品库存
    deleteCatchQuantity(row) {
      const _this = this;
      this.$modal
        .confirm("确认删除缓存中的库存吗？")
        .then(function () {
          var query = {};
          if (row) {
            query.erpGoodsId = row.erpGoodsId;
          }
          removeCatchQuantity(query).then(function () {
            _this.$modal.msgSuccess("删除缓存中的库存成功");
          });
        })
        .catch(function (err) {
          _this.$modal.msgError("删除缓存中的库存出错");
        });
    },
    // 修改到手约展示状态
    handleEvaluateStatusChange(row) {
      console.log(row.evaluate);
      var _this = this;
      updateEvaluate(row.goodsId, row.id, row.evaluate).then(function () {
        _this.$modal.msgSuccess(row.evaluate ? "已开启" : "已关闭");
      });
    },
    // 同步商品资料
    syncSku(row) {
      window.open(
        "http://www.xdyy365.com:5003/wholesale/sync-api/sync/goods/" +
          row.identifier,
        "_black"
      );
    },
    submitGoodsAlias(){
      updateAlias(this.form.id, this.form.alias).then(res=>{
        console.log(res)
        this.$modal.msgSuccess("修改成功");
        this.goodsAliasVisible = false;
      })
    },
  },
};
</script>
